// 目录管理 sys_catalog sys_catalog_sort
const db = require('../db')
const { getNowTime, formatTime } = require('../utils/index')
// 集成log4js日志
const log4js = require('../utils/log4js')
const logger = log4js.getLogger('runtime')

/**
 * 新增目录
 * @param {*} req
 * @param {*} res
 */
exports.addCatalog = (req, res) => {
  // 日期时间格式化
  req.body.create_time = req.body.create_time
    ? formatTime(req.body.create_time)
    : getNowTime()
  // 查询
  const selectSql = `select * from sys_catalog where is_delete = 0 and (code = ? or name = ?)`
  db.query(selectSql, [req.body.code, req.body.name], (err, results) => {
    if (err) return res.new_send(err)
    // 判断目录名称和目录编码是否存在
    if (results.length >= 2) return res.new_send('目录名称与目录编码已存在')
    if (results.length === 1) {
      const { code, name } = results[0]
      const { code: menu_code, name: menu_name } = req.body
      if (code === menu_code && name === menu_name) {
        return res.new_send('目录名称与目录编码已存在')
      }
      if (name === menu_name) {
        return res.new_send('目录名称已存在')
      }
      if (code === menu_code) {
        return res.new_send('目录编码已存在')
      }
    }
    // 插入数据库
    const insertSql = `insert into sys_catalog set ?`
    db.query(insertSql, req.body, (err, results) => {
      if (err) return res.new_send(err)
      if (results.affectedRows !== 1) return res.new_send('新增目录失败')
      res.send({
        status: 0,
        message: '新增目录成功',
        data: { insertId: results.insertId }
      })
    })
  })
}

/**
 * 修改目录
 * @param {*} req
 * @param {*} res
 */
exports.updateCatalog = (req, res) => {
  // 日期时间格式化
  req.body.create_time = req.body.create_time
    ? formatTime(req.body.create_time)
    : getNowTime()
  // 查询
  const selectSql = `select * from sys_catalog where id <> ? and is_delete = 0 and (code = ? or name = ?)`
  db.query(
    selectSql,
    [req.body.id, req.body.code, req.body.name],
    (err, results) => {
      if (err) return res.new_send(err)
      // 判断目录名称和目录编码是否存在
      if (results.length >= 2) return res.new_send('目录名称与目录编码已存在')
      if (results.length === 1) {
        const { code, name } = results[0]
        const { code: menu_code, name: menu_name } = req.body
        if (code === menu_code && name === menu_name) {
          return res.new_send('目录名称与目录编码已存在')
        }
        if (name === menu_name) {
          return res.new_send('目录名称已存在')
        }
        if (code === menu_code) {
          return res.new_send('目录编码已存在')
        }
      }
      //  修改数据库
      const updateSql = `update sys_catalog set ? where Id = ?`
      db.query(updateSql, [req.body, req.body.id], (err, results) => {
        if (err) return res.new_send(err)
        if (results.affectedRows !== 1) return res.new_send('更新目录失败')
        res.new_send('更新目录成功', 0)
      })
    }
  )
}

/**
 * 删除目录
 * @param {*} req
 * @param {*} res
 */
exports.deleteCatalogById = (req, res) => {
  const deleteSql = `update sys_catalog set is_delete = 1 where id = ?`
  db.query(deleteSql, req.params.id, (err, results) => {
    if (err) return res.new_send(err)
    if (results.affectedRows <= 0) return res.new_send('删除目录失败')
    res.new_send('删除目录成功', 0)
  })
}

/**
 * 获取目录列表
 * @param {*} req
 * @param {*} res
 */
exports.getCatalogLsit = (req, res) => {
  // 分页加载
  const page_num = req.query.page_num || 1 //当前的num
  const page_size = req.query.page_size || 10 //当前页的数量
  const name = req.query.name
  const params = [
    (parseInt(page_num) - 1) * parseInt(page_size),
    parseInt(page_size)
  ]
  // 查询
  const selectSql =
    `select a.*, b.username user_name from sys_catalog as a left join sys_user as b on a.user_id = b.id where a.is_delete = 0 ` +
    (name ? `and name like '%${name}%'` : '') +
    ` limit ?,?`
  db.query(selectSql, params, (err, results) => {
    if (err) return res.new_send(err)
    if (results.length > 0) {
      results.forEach((item) => {
        item.create_time = formatTime(item.create_time)
      })
    }
    // 列表数据
    let catalogs = results

    // 查询数据库总数
    const totalSql =
      'select count(*) as total from sys_catalog where is_delete = 0'
    db.query(totalSql, (err, results) => {
      if (err) return res.new_send(err)
      let total = results[0]['total'] // 总数
      res.send({
        status: 0,
        message: '获取目录列表成功',
        page_num,
        page_size,
        total,
        data: catalogs
      })
    })
  })
}

/**
 * 获取目录信息
 * @param {*} req
 * @param {*} res
 */
exports.getCatalogById = (req, res) => {
  const selectSql = `select a.*, b.username user_name from sys_catalog as a left join sys_user as b on a.user_id = b.id where a.is_delete = 0 and a.id = ?`
  db.query(selectSql, req.params.id, (err, results) => {
    if (err) return res.new_send(err)
    if (results.length > 0) {
      results.forEach((item) => {
        item.create_time = formatTime(item.create_time)
      })
    }
    res.send({
      status: 0,
      message: '获取目录信息成功',
      data: results
    })
  })
}

/**
 * 新增目录关联分类
 * @param {*} req
 * @param {*} res
 */
exports.addCatalogInSort = async (req, res) => {
  if (req.body.length > 0) {
    const selectSql = `select * from sys_catalog_sort where catalog_id = ? and sort_id = ?`
    const insertSql = `insert into sys_catalog_sort set ?`
    req.body.map(async (item) => {
      // 查询是否存在
      db.query(selectSql, [item.catalog_id, item.sort_id], (err, results) => {
        if (err) return res.new_send(err)
        if (results.length <= 0) {
          // 当数据不存在，直接新增
          db.query(insertSql, item, (err, results) => {
            if (err) return res.new_send(err)
            logger.info(
              `新增目录(${item.catalog_id})关联分类(${item.sort_id})成功...`
            )
          })
        } else {
          // 当数据存在，直接修改删除状态
          const deleteSql = `update sys_catalog_sort set is_delete = 0 where catalog_id = ? and sort_id = ?`
          db.query(
            deleteSql,
            [item.catalog_id, item.sort_id],
            (err, results) => {
              if (err) return res.new_send(err)
              logger.info(
                `新增目录(${item.catalog_id})关联分类(${item.sort_id})成功...`
              )
            }
          )
        }
      })
    })
    await res.send({
      status: 0,
      message: '目录关联分类成功'
    })
  } else {
    res.new_send('目录关联分类失败')
  }
}

/**
 * 根据Id删除目录关联分类
 * @param {*} req
 * @param {*} res
 */
exports.deleteCatalogInSortById = (req, res) => {
  const deleteSql = `update sys_catalog_sort set is_delete = 0 where catalog_id = ? and sort_id = ?`
  db.query(
    deleteSql,
    [req.body.catalog_id, req.body.sort_id],
    (err, results) => {
      if (err) return res.new_send(err)
      if (results.affectedRows <= 0) return res.new_send('删除目录关联分类失败')
      res.send({
        status: 0,
        message: '删除目录关联分类成功'
      })
    }
  )
}

/**
 * 根据目录Id查询分类列表
 * @param {*} req
 * @param {*} res
 */
exports.getCatalogInSortList = (req, res) => {
  const selectSql = `select a.*, b.catalog_id, b.sort_id, 
  case when b.catalog_id is not null then 1 else 0 end is_relevance from sys_sort as a
  left join (
    select * from sys_catalog_sort where is_delete = 0 and catalog_id = ?
  ) as b on a.id = b.sort_id where a.is_delete = 0`
  db.query(selectSql, req.params.id, (err, results) => {
    if (err) return res.new_send(err)
    res.send({
      status: 0,
      message: '获取目录关联分类列表成功',
      data: results
    })
  })
}
